package com.xiaoshou.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.codec.digest.DigestUtils;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import com.xiaoshou.util.FileUtil;
import com.xiaoshou.util.MyUUID;

public class A_InsertIntoFiles {
	private static Connection conn = null;
	private static Statement stat = null;

	public static void main(String[] args){
		/*File file = new File("C:\\Users\\Administrator\\Desktop\\原技术支持\\先天性并指连指\\先天性并指.Data");
		System.out.println(file.isFile());*/
		
		//File file = new File("C:\\Users\\Administrator\\Desktop\\原技术支持");
		
		String str = "C:\\Users\\Administrator\\Desktop\\新添加的技术支持";
		//String str1 = "C:\\Users\\Administrator\\Desktop\\已完成技术支持内容";
		File file = new File(str);
		File[] fileList = file.listFiles();
		for (File file2 : fileList) {
			
			insertInto(file2.getPath());
		}
		System.out.println(MyUUID.createUUID().toString());
		
	}

	public static void insertInto(String path){
		System.out.println("-----" + path + "---------------");
		File file = new File(path);
		if (file.isFile()) {
			// 文件路径，在截字符串
			
			String questionId = UUID.randomUUID().toString();
			String answersId = UUID.randomUUID().toString();
			String filesId = UUID.randomUUID().toString();
			
			String questionname = file.getName().substring(0, file.getName().lastIndexOf("."));
			
			String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
					.format(new Date());
			String fileNm = file.getName();
			if(fileNm.contains("'")){
				fileNm = fileNm.replaceAll("'", "\\\\'");
			}
			String fileUploadUrl = "E:\\\\\\\\apache-tomcat-7.0.25\\\\\\\\webapps\\\\\\\\xiaoshou\\\\\\\\files\\\\\\\\"
					+fileNm;
			// 存库
			try {
				Class.forName("com.mysql.jdbc.Driver");
				conn = (Connection) DriverManager.getConnection(
						"jdbc:mysql:///market", "root", "root");
				stat = (Statement) conn.createStatement();
				stat.execute("INSERT INTO question(id,questionname,questiontypeid,createtime,updatetime,userid) VALUE('"
						+ questionId+ "','"+ questionname+ "','b93424d7-7de8-499d-b206-e329ec5faa15','"+ time+ "','" + time +"','"+"admin"+ "')");
				stat.execute("INSERT INTO answers(id,content,state,createtime,updatetime,lastexamine,questionid,userid) " +
						"VALUE('"+answersId+"','答案见附件!','审核通过','"+time+"','"+time+"','admin','"+questionId+"','admin')");
				stat.execute("INSERT INTO files(id,filename,filesize,md5,fileurl,uploadtime,lastupdatetime,userid) " +
						"VALUE('"+filesId+"','"+
						fileUploadUrl.substring(fileUploadUrl.lastIndexOf("\\\\")+2, fileUploadUrl.length())+"','"+
						FileUtil.getFileSize(file.length())+"','"
						+DigestUtils.md5Hex(new FileInputStream(file))+"','"+fileUploadUrl+"','"+
						time+"','"+time+"','admin')");
				stat.execute("insert into question_files_rel(questionid,filesid) value('"+questionId+"','"+filesId+"')");
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					stat.close();
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			
		} else if (file.isDirectory()) {
			// 文件路径，在截字符串
			//String filePath = file.getPath();
			
			String questionId = UUID.randomUUID().toString();
			String answersId = UUID.randomUUID().toString();
			
			String questionname = file.getName();
			String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
					.format(new Date());
			
			// 存库
			try {
				Class.forName("com.mysql.jdbc.Driver");
				conn = (Connection) DriverManager.getConnection(
						"jdbc:mysql:///market", "root", "root");
				stat = (Statement) conn.createStatement();
				stat.execute("INSERT INTO question(id,questionname,questiontypeid,createtime,updatetime,userid) VALUE('"
						+ questionId+ "','"+ questionname+ "','b93424d7-7de8-499d-b206-e329ec5faa15','"+ time+ "','" + time +"','"+"admin"+ "')");
				stat.execute("INSERT INTO answers(id,content,state,createtime,updatetime,lastexamine,questionid,userid) " +
						"VALUE('"+answersId+"','答案见附件!','审核通过','"+time+"','"+time+"','admin','"+questionId+"','admin')");
				
				File[] fileList = file.listFiles();
				for (File file2 : fileList) {
					if(file2.isFile()){
						String fileNm = file2.getName();
						if(fileNm.contains("'")){
							fileNm = fileNm.replaceAll("'", "\\\\'");
						}
						String fileUploadUrl = "E:\\\\\\\\apache-tomcat-7.0.25\\\\\\\\webapps\\\\\\\\xiaoshou\\\\\\\\files\\\\\\\\"
								+fileNm;
						String filesId = UUID.randomUUID().toString();
						//文件的存库，与文件不同
						String sqlStr = "INSERT INTO files(id,filename,filesize,md5,fileurl,uploadtime,lastupdatetime,userid) " +
								"VALUE('"+filesId+"','"+fileUploadUrl.substring(fileUploadUrl.lastIndexOf("\\\\")+2, fileUploadUrl.length())+"','"+FileUtil.getFileSize(file2.length())+"','"
								+DigestUtils.md5Hex(new FileInputStream(file2))+"','"
								+fileUploadUrl+"','"+
								time+"','"+time+"','admin')";
						System.out.println(sqlStr);
						stat.execute(sqlStr);
						stat.execute("insert into question_files_rel(questionid,filesid) value('"+questionId+"','"+filesId+"')");
					} else if(file2.isDirectory()){
						System.out.println("这个应该不会出现");
						//压缩文件,压缩的文件,存库
						File zipFile = compressFile(file2);
						String fileNm = zipFile.getName();
						if(fileNm.contains("'")){
							fileNm = fileNm.replaceAll("'", "\\\\'");
						}
						String fileUploadUrl = "E:\\\\\\\\apache-tomcat-7.0.25\\\\\\\\webapps\\\\\\\\xiaoshou\\\\\\\\files\\\\\\\\"
								+fileNm;
						String filesId = UUID.randomUUID().toString();
						//文件的存库，与文件不同
						String sqlStr = "INSERT INTO files(id,filename,filesize,md5,fileurl,uploadtime,lastupdatetime,userid) " +
								"VALUE('"+filesId+"','"+
								fileUploadUrl.substring(fileUploadUrl.lastIndexOf("\\\\")+2, fileUploadUrl.length())+"','"+
								FileUtil.getFileSize(zipFile.length())+"','"
								+DigestUtils.md5Hex(new FileInputStream(zipFile))+"','"+fileUploadUrl+"','"+
								time+"','"+time+"','admin')";
						System.out.println(sqlStr);
						stat.execute(sqlStr);
						stat.execute("insert into question_files_rel(questionid,filesid) value('"+questionId+"','"+filesId+"')");
					}
						
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					stat.close();
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static File compressFile(File f){
			//File file = new File("F:\\test") ;  // 定义要压缩的文件夹
			File zipFile = new File(f.getPath()+".zip") ;    // 定义压缩文件名称  
			InputStream input = null ;  // 定义文件输入流  
			ZipOutputStream zipOut = null ; // 声明压缩流对象  
			try {
				zipOut = new ZipOutputStream(new FileOutputStream(zipFile)) ;  
				zipOut.setComment("这是文件的注释，请直接解压的本目录") ;  // 设置注释  
				int temp = 0 ;  
				if(f.isDirectory()){ // 判断是否是文件夹  
				    File lists[] = f.listFiles() ;   // 列出全部文件  
				    for(int i=0;i<lists.length;i++){  
				        input = new FileInputStream(lists[i]) ; // 定义文件的输入流  
				        zipOut.putNextEntry(new ZipEntry(f.getName()  
				            +File.separator+lists[i].getName())) ;  // 设置ZipEntry对象  
				        while((temp=input.read())!=-1){ // 读取内容  
				            zipOut.write(temp) ;    // 压缩输出  
				        }  
				        input.close() ; // 关闭输入流  
				    }  
				}  
				zipOut.close() ;    // 关闭输出流
				return zipFile;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return zipFile;
	}
}
